<script setup lang="ts">
import TableHead from '../TableHead.vue'
import ContextmenuBox from '../ContextmenuBox.vue'

import type {
  EnergyDataReportInformant,
  ReportColumnsItem,
} from '../../types'

import useArrowKey from '../useArrowKey'
import useContextmenu from '../useContextmenu'
import useReportCell from '../useReportCell'
import useReportRow from '../useReportRow'
import useReportSave from '../useReportSave'
import useLoadList from '../useLoadList'
import useReportInit from '../useReportInit'

import { getFlatternColumns } from '../util'
import { energyMetrologicalReviewApi } from '@/api'

const props = defineProps<{
  dataTime: string
  readonly: boolean
  informant: EnergyDataReportInformant
}>()

const columns: ReportColumnsItem[] = [
  { label: '能源种类及能源名称', prop: 'energyName', width: 140 },
  {
    label: '能源计量分级、分项',
    prop: 'B',
    children: [
      {
        label: '进出用能单位',
        prop: 'BA',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped1' },
          { label: '实配数量（台）', prop: 'realityEquipped1' },
          { label: '实际配备率（%）', prop: 'realityPercentage1' },
        ],
      },
      {
        label: '进出主要次级用能单位',
        prop: 'BB',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped2' },
          { label: '实配数量（台）', prop: 'realityEquipped2' },
          { label: '实际配备率（%）', prop: 'realityPercentage2' },
        ],
      },
      {
        label: '主要用能设备',
        prop: 'BC',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped3' },
          { label: '实配数量（台）', prop: 'realityEquipped3' },
          { label: '实际配备率（%）', prop: 'realityPercentage3' },
        ],
      },
      {
        label: '其他项目',
        prop: 'BD',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped4' },
          { label: '实配数量（台）', prop: 'realityEquipped4' },
          { label: '实际配备率（%）', prop: 'realityPercentage4' },
        ],
      },
    ],
  },
]
const flatternColumns = getFlatternColumns(columns)
const showLineNumber = ref(false)

const { lists, loading, loadList } = useLoadList(
  flatternColumns,
  () =>
    energyMetrologicalReviewApi.selectMeasurementClassification(
      props.dataTime,
    ),
  props.readonly,
)
const summary = computed(() => {
  const listsValue = toValue(lists)
  const needAccumulateValue = listsValue.map(({ data }) => {
    return data.slice(1)
  })
  return {
    uuid: uuid('temp_'),
    data: needAccumulateValue.reduce((acc, vv) => {
      acc = vv.map((vvv, iii) => {
        return {
          ...vvv,
          value: (Number(acc[iii]?.value) || 0) + Number(vvv.value),
          editable: false,
          calculable: true,
        }
      })
      return acc
    }, []),
  }
})
const { inputIndex, initInputIndex, clickCallback }
  = useReportCell()
const { left, top, rowIndex, onContextmenu }
  = useContextmenu()
const { delRow, appendRow, prependRow } = useReportRow(
  lists,
  columns,
  rowIndex,
)
const { saveStage } = useReportSave(
  lists,
  props.informant,
  energyMetrologicalReviewApi.saveOrUpdateMeasurementClassification,
  {
    dataTime: props.dataTime,
    preProcessData(data: any[]) {
      data.forEach((v) => {
        for (const key in v) {
          if (key === 'id') {
            v.id = +v.id || undefined
          }
          if (/(shouldEquipped)|(realityEquipped)|(realityPercentage)/.test(key)) {
            v[key] = Number(v[key]) || 0
          }
        }
      })
    },
  },
)

useArrowKey(inputIndex, flatternColumns.length)
useReportInit(loadList, initInputIndex)

defineExpose({
  saveStage,
})
</script>

<template>
  <div v-loading="loading">
    <div class="report-table-head">
      <table class="report-table">
        <TableHead
          :columns="columns"
          :show-line-number="showLineNumber"
        />
      </table>
    </div>
    <table class="report-table" style="height: auto">
      <tbody ref="tbody">
        <tr v-for="(item, i) in lists" :key="item.uuid">
          <th
            v-if="showLineNumber"
            class="readonly width-40px line-number"
          >
            {{ i + 1 }}
          </th>
          <td
            v-for="(d, index) in item.data"
            :key="`${item.uuid}_${index}`"
            :style="index === 0 ? 'width: 150px;' : ''"
          >
            <div v-if="!d.editable" class="span-cell">
              {{ d.value }}
            </div>
            <div v-else class="input-cell">
              <input
                v-model="d.value"
                type="text"
                @click="clickCallback"
                @contextmenu="evt => onContextmenu(evt, i)"
              >
            </div>
          </td>
        </tr>
        <tr>
          <td class="is-calculable" style="width: 150px">
            <div class="span-cell">
              合计
            </div>
          </td>
          <td
            v-for="(s, sindex) in summary.data"
            :key="sindex"
            class="is-calculable"
          >
            <div class="span-cell">
              {{ s.value }}
            </div>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="description-text">
      <p>
        注：其他项目包括：可回收利用余能、能源计量标准、自检自查、能源能量分析等项目。
      </p>
    </div>
    <ContextmenuBox
      :left="left"
      :top="top"
      @del-row="delRow"
      @prepend-row="prependRow"
      @append-row="appendRow"
    />
  </div>
</template>
